package com.ruoyi.web.controller.wechat;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.wechat.WechatConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.wechat.*;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.wechat.response.ProblemCategoryVO;
import com.ruoyi.system.domain.wechat.response.RailwayLineVO;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.wechat.IWechatAdministrativeUnitService;
import com.ruoyi.system.service.wechat.IWechatUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import javax.validation.constraints.Size;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 微信小程序公共
 *
 * @author jiexiang.sun/Jason
 * @version 1.0.0
 * @create 2022-03-03 23:16
 **/
@RestController
@Validated
@RequestMapping("/wechat")
@Slf4j
public class WechatCommonController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IWechatUserService wechatUserService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private IWechatAdministrativeUnitService wechatAdministrativeUnitService;

    @Autowired
    private ServerConfig serverConfig;

    @Value("${wechat.problem.picture_path}")
    private String picturePath;

    /**
     * filter抛出异常
     */
    @RequestMapping("/error/filter/exthrow")
    public void filterExceptionThrow(HttpServletRequest request) {
        throw new BaseException(String.valueOf(request.getAttribute("filter.error")), new Object[0]);
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/dict/getProblemCategory")
    public AjaxResult getProblemCategoryByDict() {
        List<SysDictData> data = dictTypeService.selectDictDataByType("wechat_problem_category");
        if (CollectionUtil.isEmpty(data)) {
            data = Collections.EMPTY_LIST;
        }

        List<ProblemCategoryVO> problemCategoryVOS = new ArrayList<>(data.size());
        data.forEach(dict -> {
            problemCategoryVOS.add(new ProblemCategoryVO(dict.getDictValue(), dict.getDictLabel(), dict.getRemark()));
        });
        return AjaxResult.success(problemCategoryVOS);
    }

    /**
     * 根据字典类型查询字典数据信息
     * @return
     */
    @GetMapping(value = "/dict/getRailwayLine")
    public AjaxResult getRailwayLine() {
        List<SysDictData> data = dictTypeService.selectDictDataByType("sys_railway_line");
        if (CollectionUtil.isEmpty(data)) {
            data = Collections.EMPTY_LIST;
        }

        List<RailwayLineVO> railwayLineVOS = new ArrayList<>(data.size());
        data.forEach(dict -> {
            railwayLineVOS.add(new RailwayLineVO(dict.getDictValue(), dict.getDictLabel()));
        });
        return AjaxResult.success(railwayLineVOS);
    }

    /**
     * 获取省数据
     *
     * @return
     */
    @GetMapping("getProvinces")
    public List<WechatProvince> getProvinces() {
        return wechatAdministrativeUnitService.getProvince();
    }

    /**
     * 获取市数据
     *
     * @param provinceCode
     * @return
     */
    @GetMapping("getCitys")
    public List<WechatCity> getCitys(Integer provinceCode) {
        return wechatAdministrativeUnitService.getCitys(provinceCode);
    }

    /**
     * 获取区县数据
     *
     * @param cityCode
     * @return
     */
    @GetMapping("getAreas")
    public List<WechatArea> getAreas(Integer cityCode) {
        return wechatAdministrativeUnitService.getAreas(cityCode);
    }


    /**
     * 获取街道数据
     *
     * @param areaCode
     * @return
     */
    @GetMapping("getStreets")
    public List<WechatStreet> getStreets(Integer areaCode) {
        return wechatAdministrativeUnitService.getStreets(areaCode);
    }

    @GetMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/csv; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"abcdefg.csv\";charset=utf-8");
        CsvWriter csvWriter = CsvUtil.getWriter(response.getWriter());
        csvWriter.writeLine("a", "b","d def");
        csvWriter.write(
                new String[]{"a1", "b1", "c1"},
                new String[]{"a2", "b2", "c2"},
                new String[]{"a3", "b3", "c3"}
        );

        csvWriter.writeLine("a", "b","d def");
        csvWriter.writeLine();
        csvWriter.writeLine("a", "b","d def");
        csvWriter.close();
    }

    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file){
        String filePath ;
        try {
            // 上传文件路径
            String profile = RuoYiConfig.getProfile() + picturePath;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(profile, file);
            filePath = serverConfig.getUrl() + fileName;
        } catch (IOException e) {
            log.error("问题图片上传发生错误，错误消息={}", e.getMessage(), e);
            throw new GlobalException(e.getMessage());
        }

        return AjaxResult.success(filePath);
    }
}
